<?php

namespace App\Console\Commands\User;

use App\Kuafu\User\Service\NewUserService;
use App\Library\FeiShu\SendFs;
use App\Library\KfHttp\TigerCurl;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;
use Ritaswc\LarkCardMessageBuilder\CardMessageBuilder;
use Ritaswc\LarkCardMessageBuilder\Tag;

class MerchantUserActiveCommand extends Command
{
    protected $signature   = 'user:merchant-user-active {date?}';
    protected $description = '商家app用户数据推送';

    public function handle()
    {
        $date = $this->argument('date');
        if (!$date) {
            $date = date('Y-m-d', strtotime('-1 day'));
        }

        $yesterday = date('Y-m-d', strtotime($date . ' -1 day'));
        $dateStr   = date('m月d日', strtotime($date));

        // date日活
        $dateObj               = (new NewUserService(0, $date));
        $dateDau               = $dateObj->dau();
        $dateNewUser           = $dateObj->newUser();
        $dateNewUserRemainRate = $dateObj->newNextRemainRate();

        // date-1日活
        $yesterdayObj               = (new NewUserService(0, $yesterday));
        $yesterdayDau               = $yesterdayObj->dau();
        $yesterdayNewUser           = $yesterdayObj->newUser();
        $yesterdayNewUserRemainRate = $yesterdayObj->newNextRemainRate();

        // tiger数据
        $tops = TigerCurl::getIns()
                         ->do('internal/article/articleTop', ['date' => $date, 'limit' => 10], 'GET')['data'] ?? [];

        $envSuffix = config('app.env') == 'prod' ? '' : '【' . config('app.env') . '】';

        $cardMessageBuilder = (new CardMessageBuilder('夸父商家数据统计：' . $date . $envSuffix))
            ->template('blue')
            ->addElement(Tag::markdown("**{$dateStr} 夸父商家首页用户数据：**")->textAlign('left'));

        // 日活、新用户、新用户次日留存
        $column1 = [
            $this->columnData('日活', $dateDau, $yesterdayDau),
            $this->columnData('新用户', $dateNewUser, $yesterdayNewUser),
            $this->columnData('新用户次日留存', $dateNewUserRemainRate, $yesterdayNewUserRemainRate, '%'),
        ];

        $tmp = Tag::columnSet();
        foreach ($column1 as $column) {
            $tmp->addColumn(
                Tag::column()
                   ->width('weighted')
                   ->weight(1)
                   ->addElement(Tag::markdown("{$column[0]}\n**{$column[1]}**\n<font color='{$column[2]}'>较昨日{$column[3]}</font>")));
        }
        $cardMessageBuilder->addElement($tmp);

        // 点击率
        $column2 = [
            $this->columnData('Banner点击', $tops['click'][1] ?? 0, $tops['clickYesterday'][1] ?? 0),
            $this->columnData('专题点击', $tops['click'][2] ?? 0, $tops['clickYesterday'][2] ?? 0),
            $this->columnData('内容点击', $tops['click'][3] ?? 0, $tops['clickYesterday'][3] ?? 0),
        ];

        $tmp = Tag::columnSet();
        foreach ($column2 as $column) {
            $tmp->addColumn(
                Tag::column()
                   ->width('weighted')
                   ->weight(1)
                   ->addElement(Tag::markdown("{$column[0]}\n**{$column[1]}**\n<font color='{$column[2]}'>较昨日{$column[3]}</font>")));
        }
        $cardMessageBuilder->addElement($tmp);

        $cardMessageBuilder->addElement(Tag::markdown("**{$dateStr} 夸父商家热门内容top10：**")->textAlign('left'))
                           ->addElement(
                               Tag::columnSet()
                                  ->addColumn(
                                      Tag::column()->width('weighted')->weight(1)->verticalAlign('center')->addElement(
                                          Tag::markdown("**展示**")->textAlign('left')
                                      )
                                  )
                                  ->addColumn(
                                      Tag::column()->width('weighted')->weight(1)->verticalAlign('center')->addElement(
                                          Tag::markdown("**阅读**")->textAlign('left')
                                      )
                                  )
                                  ->addColumn(
                                      Tag::column()->width('weighted')->weight(1)->verticalAlign('center')->addElement(
                                          Tag::markdown("**点赞**")->textAlign('left')
                                      )
                                  )
                                  ->addColumn(
                                      Tag::column()->width('weighted')->weight(1)->verticalAlign('center')->addElement(
                                          Tag::markdown("**分享**")->textAlign('left')
                                      )
                                  )
                                  ->addColumn(
                                      Tag::column()->width('weighted')->weight(1)->verticalAlign('center')->addElement(
                                          Tag::markdown("**收藏**")->textAlign('left')
                                      )
                                  )
                           );

        // TOP 10
        foreach ($tops['articleTop'] as $k => $top) {
            $cardMessageBuilder->addElement(
                Tag::note()->add(
                    Tag::noteText($k + 1 . '. ' . $top['title'])
                )
            )
                               ->addElement(
                                   Tag::columnSet()
                                      ->backgroundStyle('default')
                                      ->flexMode('none')
                                      ->addColumn(
                                          Tag::column()->width('weighted')->weight(1)->verticalAlign('center')
                                             ->addElement(
                                                 Tag::markdown($top['showCount'] ?? 0)->textAlign('left')
                                             )
                                      )
                                      ->addColumn(
                                          Tag::column()->width('weighted')->weight(1)->verticalAlign('center')
                                             ->addElement(
                                                 Tag::markdown($top['readCount'] ?? 0)->textAlign('left')
                                             )
                                      )
                                      ->addColumn(
                                          Tag::column()->width('weighted')->weight(1)->verticalAlign('center')
                                             ->addElement(
                                                 Tag::markdown($top['likeCount'] ?? 0)->textAlign('left')
                                             )
                                      )
                                      ->addColumn(
                                          Tag::column()->width('weighted')->weight(1)->verticalAlign('center')
                                             ->addElement(
                                                 Tag::markdown($top['shareCount'] ?? 0)->textAlign('left')
                                             )
                                      )
                                      ->addColumn(
                                          Tag::column()->width('weighted')->weight(1)->verticalAlign('center')
                                             ->addElement(
                                                 Tag::markdown($top['collectCount'] ?? 0)->textAlign('left')
                                             )
                                      )
                               );
        }

        $cardBodyArray = $cardMessageBuilder->build();

        BuildFs::newRobot(SendFs::ROBOT_FS_APP_USER_DATA, BuildFs::MSG_TYPE_CARD)->setCardContent($cardBodyArray)->send();
    }

    private function numberFormat(float $number): string
    {
        $prefix = '';
        if ($number > 0) {
            $prefix = '+';
        }

        return $prefix . number_format($number, 0, '.', ',');
    }

    private function columnData(string $title, $todayNum, $yesterdayNum, string $suffix = ''): array
    {
        $compareNum      = $todayNum - $yesterdayNum;
        $compareDauColor = $compareNum >= 0 ? 'red' : 'green';

        return [
            $title,
            $this->numberFormat($todayNum) . $suffix,
            $compareDauColor,
            $this->numberFormat($compareNum) . $suffix
        ];
    }
}
